package com.okilo.online.app.common

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.net.toUri
import com.okilo.online.app.BuildConfig
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.base.OkiloBaseAct
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.event.OkiloEventSubscriber
import com.okilo.online.app.request.HttpErrorCode
import com.okilo.online.app.request.HttpHelper
import com.okilo.online.app.request.IHttpCallback
import com.okilo.online.app.request.NetworkManager
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.act.OkiloAdviceTypeAct
import com.okilo.online.app.dialog.OkiloCServiceDlog
import com.okilo.online.app.dialog.OkiloTipsDlog
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

/**
 * CommonActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:32
 * @Annotation：
 */
abstract class OkiloComAct: OkiloBaseAct(), OkiloEventSubscriber, IOkiloComView,EasyPermissions.PermissionCallbacks {
    //是否记录埋点
    private var isPageViewRecorded = false
    //客服
    var okiloCustomerDlog: OkiloCServiceDlog? = null
    var errorDialog: OkiloTipsDlog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        NetworkManager.registerActivity(this)
        super.onCreate(savedInstanceState)
    }

    override fun getAct(): OkiloComAct {
        return this
    }

    override fun onBackAction() {
        super.onBackAction()
        addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.OKILO_CLICK_BACK, pageName)
    }

    override fun setupOkiloEventListeners() {
        //客服
        setRightButtonClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.CUSTOMER, pageName)
                sOkiloAppServiceDialog(pageName)
            }
        })
    }

    /**
     * 错误提示
     */
    fun sOkiloAppErrorDialog(tips: String, eventRemark: String = ""){
        if (errorDialog == null){
            errorDialog = OkiloTipsDlog(this,eventRemark)
        }
        errorDialog?.let { dialog ->
            if (dialog.isShowing){
                return
            }
            dialog.setOnClick(object : OkiloTipsDlog.IOkiloTipsClickCallback{
                override fun onClick(view: View?) {

                }
            })
            dialog.show()
            dialog.iOkiloDlogTipsDoubleButton(false)
            dialog.sOkiloDlogTipsMsgText(tips)
        }
    }

    /**
     * 客服
     */
    fun sOkiloAppServiceDialog(eventRemark: String = ""){
        if (okiloCustomerDlog == null){
            okiloCustomerDlog = OkiloCServiceDlog(this)
                .sOkiloCServiceEventRemark(eventRemark)
                .sOkiloCServiceClickCallback(object : OkiloCServiceDlog.ICServiceDlogCallback{
                    override fun onOkiloCServiceMobileDialClick(phoneNumber: String) {
                        sOkiloCustomerServiceMobileDial(phoneNumber)
                    }
                    override fun onOkiloCServiceFeedbackClick() {//Feedback
                        sOkiloCustomerServiceFeedbackClick()
                    }
                })
            okiloCustomerDlog?.setCancelable(true)
            okiloCustomerDlog?.setCanceledOnTouchOutside(true)
        }
        okiloCustomerDlog?.show()
    }

    /**
     * 拨号
     */
    private fun sOkiloCustomerServiceMobileDial(mobile: String){
        val intent = Intent(Intent.ACTION_DIAL).apply {
            data = "tel:$mobile".toUri()
        }
        // 检查是否有应用可以处理这个 Intent
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        } else {
            // 处理没有拨号应用的情况
            showOkiloToast("No dialer app found")
        }
    }

    /**
     * feedback
     */
    private fun sOkiloCustomerServiceFeedbackClick(){
        //当前栈顶是 意见反馈类型
        if (OkiloActStackManager.isCurrentActivity(OkiloAdviceTypeAct::class.java)){
            return
        }
        val intent = Intent(this, OkiloAdviceTypeAct::class.java)
        startActivity(intent)
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        HttpHelper.post(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        callback.onRequestSuccess(data)
                    }
                    else -> {
                        callback.onRequestError(data)
                        hideOkiloLoading()
                        val msg = data.optString("msg")
                        showOkiloToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                hideOkiloLoading()

                val errorCode = error.optInt("errorCode")
                if (HttpErrorCode.isBusinessError(errorCode)) {
                    // 业务错误，显示给用户
                    showOkiloToast(error.optString("errorMsg"))
                }
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
            }
        })
    }

    /**
     * 添加埋点
     */
    fun addEventPointRequestAction(eventName: String, eventRemark: String? = "") {
        HttpHelper.addPoint(eventName,eventRemark)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: OkiloEventData){
        OkiloApplication.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onOkiloPublishEvent(event: OkiloEventData) {
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("onPermissionsGranted, code: $requestCode , permissions : $perms")
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        OkiloLog.i("onPermissionsDenied code: $requestCode , permissions : $perms")
    }

    override fun onStart() {
        super.onStart()
//        HttpHelper.setTag(this)
        OkiloApplication.app.publisher.register(this)
    }

    override fun onResume() {
        super.onResume()
        NetworkManager.onActivityResumed(this)
        if (!isPageViewRecorded) {
            isPageViewRecorded = true
            trackOkiloPageStart()
        }
    }

    override fun onPause() {
        super.onPause()
        okiloCustomerDlog?.dismiss()
        errorDialog?.dismiss()
        if (isFinishing) {
            trackOkiloPageEnd()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        okiloCustomerDlog = null
        errorDialog = null
        HttpHelper.cancelTag(this)
        OkiloApplication.app.publisher.detach(this)
        NetworkManager.unregisterActivity(this)
    }

    /**
     * 启动埋点
     */
    private fun trackOkiloPageStart() {
        if (enablePageTrack){
            addEventPointRequestAction("${BuildConfig.appName}_${pageName}_start".uppercase())
        }
    }

    /**
     * 关闭埋点
     */
    private fun trackOkiloPageEnd() {
        if (enablePageTrack){
            addEventPointRequestAction("${BuildConfig.appName}_${pageName}_end".uppercase())
        }
    }
}